<template>
  <!-- 打印装箱单-->
  <a-modal :width="1200" top="8vh" v-model:visible="showPrintDialog" title="打印装箱单" title-align="start" :mask-closable="false" @cancel="closedDialog" :footer="false">
    <div class="flex-c">
      <p>打印箱单格式：</p>
      <a-select v-model="boxType" placeholder="选择箱单格式" size="small" style="width: 400px; margin-right: 20px">
        <a-option v-for="(type, i) in boxTypeList" :key="i" :value="type" :label="type" />
      </a-select>
      <a-button type="primary" size="small" @click="getBoxLabel" :loading="getLoading">获取箱单</a-button>
    </div>
    <div class="flex-c" style="margin: 10px 0">
      <ChoosePrintList ref="choosePrintRef" :showDom="false" :selectWidth="200" direction="row" @getLodop="getLodop">
        <template #ipUrl>
          <p style="color: var(--color-text-1)">云主机：</p>
        </template>
        <template #bridgelabel>
          <p style="color: var(--color-text-1)">打印服务器：</p>
        </template>
        <template #printerlabel>
          <p style="color: var(--color-text-1)">服务下的打印机：</p>
        </template>
      </ChoosePrintList>
      <a-button type="primary" size="small" style="margin: 0 10px" @click="toPrint">打印</a-button>
      <a-button size="small" @click="downloadFile">下载装箱单</a-button>
    </div>
    <div class="preview-w">
      <iframe v-if="pdfUrl" :src="pdfUrl" width="100%" height="100%"></iframe>
      <p v-else>显示获取到的装箱单</p>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import ChoosePrintList from '@/components/Print/choosePrintList.vue'
  import { getFbaShipmentPackingLabels, getFbaShipmentAmazonPackingLabels } from '@/api/purchase'
  import { pdfToBlob } from '@/api/base'
  import FileSaver from 'file-saver'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentData: {
      type: Object,
      default: () => {},
    },
    api: {
      type: String,
      default: 'getFbaShipmentPackingLabels',
    },
  })

  const showPrintDialog = ref(props.isShow)
  const getLoading = ref(false)
  const choosePrintRef = ref()
  const pdfUrl = ref()
  const boxType = ref('PackageLabel_Letter_2')
  const boxTypeList = ['PackageLabel_Letter_2', 'PackageLabel_Letter_4', 'PackageLabel_Letter_6', 'PackageLabel_Letter_6_CarrierLeft', 'PackageLabel_A4_2', 'PackageLabel_A4_4', 'PackageLabel_Plain_Paper', 'PackageLabel_Plain_Paper_CarrierBottom', 'PackageLabel_Thermal', 'PackageLabel_Thermal_Unified', 'PackageLabel_Thermal_NonPCP', 'PackageLabel_Thermal_No_Carrier_Rotation']
  let LODOP: any = {}
  const apiMap = {
    getFbaShipmentPackingLabels: getFbaShipmentPackingLabels,
    getFbaShipmentAmazonPackingLabels: getFbaShipmentAmazonPackingLabels,
  }

  // 关闭
  function closedDialog() {
    showPrintDialog.value = false
    emit('closed')
  }
  function getLodop(val: any) {
    LODOP = val
  }
  // 获取箱单
  async function getBoxLabel() {
    if (!boxType.value) {
      Message.error('请选择装箱格式')
      return
    }
    getLoading.value = true
    const res: any = await apiMap[props.api]({
      id: props.currentData.id,
      pageType: boxType.value,
    })
    getLoading.value = false
    // pdfUrl.value = 'https://cdn2.selleroa.com/yfni/test/16977155370996980c8.pdf'
    pdfUrl.value = res?.data
  }
  // 下载箱单
  function downloadFile() {
    if (!pdfUrl.value) return
    FileSaver.saveAs(pdfUrl.value, '箱单.pdf')
  }
  // 开始打印
  async function toPrint() {
    if (!pdfUrl.value) return
    let url = await downloadPdf()
    LODOP.PRINT_INIT('打印箱单')
    //  指定打印机设备
    let { type, bridgeIDandName, printerIndex } = choosePrintRef.value.getBridgeInfo()
    if (type === 1) {
      LODOP.SET_BRIDGE_INDEX(bridgeIDandName + ',' + printerIndex)
    } else {
      LODOP.SET_PRINTER_INDEX(printerIndex)
    }

    LODOP.ADD_PRINT_PDF(0, 0, '100%', '100%', url)
    LODOP.PREVIEW()
  }

  async function downloadPdf() {
    if (!pdfUrl.value) return
    const res: any = await pdfToBlob(pdfUrl.value)
    if (!res) return
    let baseUrl: any = await getBase64(res.data)

    return baseUrl?.split(',')?.[1]
  }
  function getBase64(blob: any) {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader()
      fileReader.onload = (e: any) => {
        resolve(e.target.result)
      }
      // readAsDataURL
      fileReader.readAsDataURL(blob)
      fileReader.onerror = () => {
        reject(new Error('blobToBase64 error'))
      }
    })
  }
</script>
<style lang="less" scoped>
  .preview-w {
    border: 1px solid #ddd;
    height: calc(84vh - 160px);
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
